#!/usr/bin/env bash

# nginx配置文件
function nginx_config() {
  echo -e "开始创建配置文件……\n"
  echo -e "创建临时容器从容器中复制配置文件\n"
  docker run -p 80:80 --name $application -d $image:$version &>/dev/null
  sleep 2
  docker cp $application:/etc/nginx/nginx.conf ${applicationPath}/conf/nginx.conf &>/dev/null
  docker cp $application:/etc/nginx/conf.d ${applicationPath}/conf/conf.d &>/dev/null
  docker cp $application:/usr/share/nginx/html ${applicationPath}/ &>/dev/null
  sleep 1
  echo -e "删除$application临时容器"
  docker stop $application
  sleep 1
  docker rm -f $application

  ls ${applicationPath}/conf | grep nginx.conf &>/dev/null
  if [ $? -eq 0 ]; then
    echo -e "相关配置文件创建成功！\n\n"
  else
    echo "相关配置文件创建失败！"
    exit
  fi
}

# 判断容器是否启动成功
function nginx_successOrNot() {
  echo_sleep "docker run命令:\n $dockerRunCmd \n" 2
  if [[ -n $(docker ps -q -f "name=^$application$") ]]; then
    echo -e "$application 容器启动成功"
    echo -e "\t端口号：$port"
    echo -e "\t版本号：$version"
    echo -e "\t容器名称：$application"
    echo -e "\t本地映射路径：$applicationPath"
    echo -e "进入容器使用命令：docker exec -it $application /bin/bash"
    echo -e "web页面访问地址: http://host:${port}"
  else
    log_error "$application 容器启动失败,请检查docker run命令是否有误,端口是否被占用"
  fi
}

# 安装nginx
function nginx_install() {
  application="nginx"                         # 应用名称,docker ps中显示的名称
  image="nginx"                               # docker仓库中镜像名称
  applicationPath="/opt/nginx/${application}" # 本地映射文件路径
  port="80"                                   # 对外映射的端口号
  version="latest"                            # 镜像版本号,默认为最新版本
  dockerRunCmd=""                             # 最后执行的docker run命令

  echo -e "\n=========================开始安装Nginx========================="

  echo_yellow "1.检测是否存在 ${image} 容器"
  docker_delExisting ${image}

  echo_yellow "2.开始拉取镜像文件"
  docker_pull

  echo_yellow "3.开始创建本地映射目录"
  create_file_path conf logs html

  echo_yellow "4.开始创建配置文件"
  nginx_config

  echo_yellow "5.创建并启动docker容器"
  port=$(read_input "请输入需要映射的端口(默认为 ${port})：" ${port})
  application=$(read_input "请输入容器的名称(默认为 ${application})：" ${application})

  echo -e "${application}启动中,请等待......"

  dockerRunCmd="docker run --restart=always --privileged=true \
	-p $port:80 \
	--name $application \
	-v $applicationPath/conf/nginx.conf:/etc/nginx/nginx.conf \
	-v $applicationPath/conf/conf.d:/etc/nginx/conf.d \
	-v $applicationPath/logs:/var/log/nginx \
	-v $applicationPath/html:/usr/share/nginx/html \
	-v /etc/localtime:/etc/localtime:ro \
	-d $image:$version &> /dev/null"
  eval $dockerRunCmd

  echo_yellow "6.检测容器是否启动成功"
  nginx_successOrNot

  echo -e "=========================安装Nginx结束========================="
}
